package org.tao.lightningmq.client.consumer;

import com.alibaba.fastjson.JSON;
import org.tao.lightningmq.client.netty.BrokerRemoteRespHandler;
import org.tao.lightningmq.common.dto.CreateTopicReqDTO;
import org.tao.lightningmq.common.enums.BrokerEventCode;
import org.tao.lightningmq.common.event.EventBus;
import org.tao.lightningmq.common.remote.BrokerNettyRemoteClient;
import org.tao.lightningmq.common.tcp.TcpMsg;

import java.io.Closeable;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author lht
 * @date 2025/1/22 - 17:26
 * @description:
 */
public class CreateTopicClient implements Closeable {

    private BrokerNettyRemoteClient brokerNettyRemoteClient;

    public CreateTopicClient(String brokerAddress) {
        String[] brokerAddr = brokerAddress.split(":");
        String ip = brokerAddr[0];
        Integer port = Integer.valueOf(brokerAddr[1]);
        brokerNettyRemoteClient = new BrokerNettyRemoteClient(ip, port);
        brokerNettyRemoteClient.buildConnection(new BrokerRemoteRespHandler(
                new EventBus("mq-client-eventbus")));
    }

    public void createTopic(String topic) {
        CreateTopicReqDTO createTopicReqDTO = new CreateTopicReqDTO();
        createTopicReqDTO.setTopic(topic);
        createTopicReqDTO.setQueueSize(3);
        TcpMsg respMsg = brokerNettyRemoteClient.sendSyncMsg(new TcpMsg(BrokerEventCode.CREATE_TOPIC.getCode(), JSON.toJSONBytes(createTopicReqDTO)), UUID.randomUUID().toString());
        System.out.println("create topic resp:" + JSON.toJSONString(respMsg));
    }

    @Override
    public void close() {
        brokerNettyRemoteClient.close();
    }
}
